<template>
  <div>
    <!-- 查询组件 -->
    <el-form :inline="true" :model="searchMap" ref="ruleForm" class="demo-form-inline">
      <el-form-item prop='cardNum'>
        <el-input v-model="searchMap.cardNum" placeholder="会员卡号"></el-input>
      </el-form-item>
      <el-form-item prop='name'>
        <el-input v-model="searchMap.name" placeholder="会员姓名"></el-input>
      </el-form-item>
      <el-form-item prop='payType'>
        <el-select v-model="searchMap.payType" placeholder="支付类型" style="width:110px">
          <el-option v-for='item in payTypeOptions' :key='item.type' :label="item.name" :value="item.type"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop='birthday'>
        <el-date-picker type="date" placeholder="出生日期" v-model="searchMap.birthday" style="width: 100%;"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <!-- 查询 -->
        <el-button type='primary' icon="el-icon-search" circle @click="inquireMember"></el-button>
        <!-- 新增 -->
        <el-button type="info" icon='el-icon-edit-outline' circle @click="addBefore"></el-button>
        <!-- 重置 -->
        <el-button icon='el-icon-refresh' circle @click="resetForm('ruleForm')"></el-button>
      </el-form-item>
    </el-form>

    <!-- 表格组件 -->
    <el-table
      :data="tableData"
      border
      stripe
      max-height='420'
      style="width: 100%">
      <el-table-column
        fixed
        type='index'
        label="序号"
        width="60">
      </el-table-column>
      <el-table-column
        prop="cardNum"
        label="会员卡号"
        width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="70">
      </el-table-column>
      <el-table-column
        prop="birthday"
        label="生日"
        width="120">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="电话号码"
        width="180">
      </el-table-column>
      <el-table-column
        prop="integral"
        label="可用积分"
        width="120">
      </el-table-column>
      <el-table-column
        prop="money"
        label="余额"
        width="120">
      </el-table-column>
      <el-table-column
        label="支付类型"
        width="80">
        <template slot-scope="scope">
          <span>{{scope.row.payType | payTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址"
        min-width="340">
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="100">
        <template slot-scope="scope">
          <!-- scope.row：当前行的会员的所有信息 -->
          <el-button @click="editBefore(scope.row)" type="success" size="small" icon="el-icon-edit" circle></el-button>
          <el-button @click="deleteMember(scope.row)" type="danger" size="small" icon="el-icon-delete" circle></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 新增会员、编辑会员对话框组件 -->
    <el-dialog :title="MemId?'编辑会员':'新增会员'" :visible.sync="dialogFormVisible" width="600px">
      <el-form :model="form" ref="Form" :rules="rules" status-icon>
        <el-form-item prop='cardNum' label="会员卡号" :label-width="formLabelWidth">
          <el-input style='width:400px' v-model="form.cardNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop='name' label="会员姓名" :label-width="formLabelWidth">
          <el-input style='width:400px' v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop='birthday' label="会员生日" :label-width="formLabelWidth">
          <el-date-picker v-model="form.birthday" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item prop='phone' label="手机号码" :label-width="formLabelWidth">
          <el-input style='width:400px' v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop='money' label="开卡金额" :label-width="formLabelWidth">
          <el-input style='width:400px' v-model="form.money" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop='integral' label="可用积分" :label-width="formLabelWidth">
          <el-input style='width:400px' v-model="form.integral" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop='address' label="会员地址" :label-width="formLabelWidth">
          <el-input style='width:400px' v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop='payType' label="支付类型" :label-width="formLabelWidth">
          <el-select v-model="form.payType" placeholder="请选择支付类型">
            <el-option v-for='item in payTypeOptions' :key='item.type' :label="item.name" :value="item.type"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取消</el-button>
        <el-button type="primary" @click="MemId?editMember(MemId):addMember('Form')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

// 设置支付类型转换(全局)
const payTypeOptions = [
  {
    type:"1",
    name:'现金'
  },
  {
    type:"2",
    name:'微信'
  },
  {
    type:"3",
    name:'支付宝'
  },
  {
    type:"4",
    name:'银行卡'
  },
]

export default{
  data(){
    /* 自定义正则 */
    /* 1.手机号码 */
    var checkPhone = (rule, value, callback) => {
      if(value === '') {
        callback(new Error('请输入手机号码！'));
      /* }else if(!/^1(3|4|5|6|7|8)\d{9}$/.test(value)){
        callback(new Error('请输入正确的11位手机号码！')); */
      }else{
        callback();
      }
    };
    /* 2.会员卡号 */
    var checkCardNum = (rule, value, callback) => {
      if(value === '') {
        callback(new Error('请输入会员卡号！'));
      /* }else if(!/^\d{16}$/.test(value)){
        callback(new Error('请输入正确的16位数字卡号！')); */
      }else{
        callback();
      }
    };
    /* 3.会员姓名 */
    var checkName = (rule, value, callback) => {
      if(value === '') {
        callback(new Error('请输入会员卡号！'));
      }else if(!/^[\u0391-\uFFE5A-Za-z]+$/.test(value)){
        callback(new Error('请输入正确的中英文姓名！'));
      }else{
        callback();
      }
    };
    return {
      tableData: [],
      currentPage:1,    // 当前页
      pageSize:10,      // 一页显示条数
      total:0,          // 总数据数量
      searchMap:{       // 多条件查询
        cardNum:'',
        name:'',
        payType:'',
        birthday:''
      },
      /* 新增会员表单属性 */
      dialogFormVisible:false,    // 新增表单默认关闭
      form: {
        cardNum: '',
        name: '',
        birthday: '',
        phone: '',
        money: 0,
        integral: '',
        address:'',
        payType: ''
      }, 
      resetData:{
        cardNum: '',
        name: '',
        birthday: '',
        phone: '',
        money: '',
        integral: '',
        address:'',
        payType: ''
      },
      formLabelWidth: '100px',
      /* 支付类型 */
      payTypeOptions,
      /* 新增会员正则 */
      rules:{
        phone: [
          { required: true, validator: checkPhone, trigger: "blur" }
        ],
        cardNum:[
          { required: true, validator: checkCardNum, trigger: "blur" }
        ],
        name:[
          { required: true, validator: checkName, trigger: "blur" }
        ]
      },
      /* 新增会员or修改会员开关 */
      MemId:null //  默认新增
    }
  },
  methods:{
    /* 1.加载渲染首页会员列表信息(测试) */
    /* async getMemberList(){
      
      const {data} = await this.$request.get(`/member/list`)
      this.tableData = data.data;
    }, */
    /* 6.分页数据 */
    async getsearch(){
      
      const {data} = await this.$request({
        url:`/member/list/search/${this.currentPage}/${this.pageSize}`,
        method:'get',
        data:this.searchMap
      })
      this.tableData = data.data.rows;
      this.total = data.data.total;
    },
    /* 2.编辑会员前处理：把row的数据赋值给form */
    async editBefore(row){
      this.dialogFormVisible = true;
      /* 清除校验结果 */
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
      this.MemId = row.id;
      const {data} = await this.$request({
          url:`/member/${this.MemId}`,
          method:'get'
      });
      if(data.flag){
        this.form = data.data;
      }else{
        this.$notify({
            title: '失败',
            message: '获取会员信息失败！',
            type: 'error'
        });
      }
    },
    /* 3.删除会员 */
    async deleteMember(row){
      try{
        let result =  await this.$confirm('此操作将永久该会员信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        /* 发送请求 */
        
        const {data} = await this.$request({
          url:`/member/${row.id}`,
          method:'delete'
        })
        /* 根据返回信息进行对应操作 */
        if(data.flag){
          this.$notify({
            title: '成功',
            message: '删除成功！',
            type: 'success'
          });
          /* 删除成功后重新发送请求渲染列表 */
          this.getsearch()
        }else{
          this.$notify({
            title: '失败',
            message: '删除会员失败，请稍后重新删除！',
            type: 'error'
          });
        }
      }catch(err){
          this.$notify.info({
            title: '取消',
            message: '已取消删除！'
          });
      }
      
    },
    /* 4.一页显示条数功能 */
    handleSizeChange(size){
      this.pageSize = size;
      this.getsearch();
    },
    /* 5.页面跳转功能 */
    handleCurrentChange(page){
      this.currentPage = page;
      this.getsearch();
    },
    /* 7.查询 */
    inquireMember(){
      this.getsearch();
    },
    /* 8.新增会员 */
    addMember(formName){
      this.$refs[formName].validate(async (valid)=>{
        /* 所有正则都通过再发送请求 */
        if(valid){
          
          const {data} = await this.$request({
            url:`/member`,
            method:'post',
            data:this.form
          })
          /* 根据返回信息判断是否添加成功 */
          if(data.flag){
            this.$notify({
              title: '成功',
              message: '添加会员成功！',
              type: 'success'
            });
            this.$refs['Form'].resetFields();
          }else{
            this.$notify({
              title: '失败',
              message: '添加会员失败，请稍后重新添加！',
              type: 'error'
            });
            return
          }
        }else{
          this.$notify({
            title: '失败',
            message: '必填项未填写或者填写内容不符合要求！',
            type: 'error'
          });
          return
        }
        this.dialogFormVisible = false
      })
    },
    /* 9.重置 */
    resetForm(ruleForm){
      this.$refs[ruleForm].resetFields();
    },
    /* 10.新增会员前处理 */
    addBefore(){
      this.MemId = null;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["Form"].resetFields();
      });
    },
    /* 11.编辑会员 */
    async editMember(MemId){
      
      const {data} = await this.$request({
        url:`/member/${MemId}`,
        method:'put',
        data:this.form
      })
      if(data.flag){
        this.$notify({
          title: '成功',
          message: '修改会员成功！',
          type: 'success'
        });
        this.$refs['Form'].resetFields();
      }else{
        this.$notify({
          title: '失败',
          message: '修改失败，请稍后重新修改！',
          type: 'error'
        });
        return
      }
      
      this.dialogFormVisible = false;
    }
  },
  created(){
    // this.getMemberList();
    this.getsearch();
  },
  /* 局部过滤器 */
  filters:{
    /* 过滤转换类型 */
    payTypeFilter(type){
      return payTypeOptions.filter(item=>item.type == type)[0].name
    }
  }

}
</script>

<style>
  .el-form{
    padding-top: 10px;
  }
  .el-pagination{
    padding-top: 15px!important;
  }
</style>